﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ScreenMonitor.Common.API;
using System.Diagnostics;
using System.IO;

namespace ScreenMonitor.Common.Window
{

    /// <summary>
    /// 进程窗体信息对象
    /// </summary>
    public class WindowInfoObject : MemoryStreamSendableObjectBase<WindowInfoObject>
    {

        /// <summary>
        /// 窗体标题
        /// </summary>
        public string Title { get; internal set; }

        /// <summary>
        /// 窗体句柄
        /// </summary>
        public int Hwnd { get;internal set; }

        /// <summary>
        /// 进程Id
        /// </summary>
        public int ProcessId { get; internal set; }

        public WindowInfoObject()
        {
        }

        public WindowInfoObject(string Title,int Hwnd,int ProcessId)
        {
            this.Title = Title;
            this.Hwnd = Hwnd;
            this.ProcessId = ProcessId;
        }

        public override void ToStream(BinaryWriter sw)
        {
            sw.Write(this.Title);
            sw.Write(this.Hwnd);
            sw.Write(this.ProcessId);
            sw.Flush();
        }

        public override void FromStream(BinaryReader sr)
        {
            this.Title = sr.ReadString();
            this.Hwnd = sr.ReadInt32();
            this.ProcessId = sr.ReadInt32();
        }

    }

    /// <summary>
    /// 表示与窗体相关函数的集合
    /// </summary>
    public static class Window
    {
        /// <summary>
        /// 取得当前系统所有窗体的信息对象
        /// </summary>
        /// <returns></returns>
        public static List<WindowInfoObject> GetAllWindowInfo()
        {
            List<WindowInfoObject> list = new List<WindowInfoObject>();
            Process[] processes = Process.GetProcesses();
            foreach(Process process in processes)
            {
                WindowInfoObject obj = new WindowInfoObject();
                obj.ProcessId = process.Id;
                obj.Title = process.MainWindowTitle;
                obj.Hwnd = process.MainWindowHandle.ToInt32();
            }
            return list;
        }
    }
}
